<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/19
 * Time: 13:33
 */

namespace app\admin\model;

use app\admin\model\User;


class RoomProfit extends DataBase
{
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';
    protected $name = 'room_profit';


//    public function getAttrCreateTime($name, &$item = null)
//    {
//    }

    public function indexData()
    {
        $map = ['u_id'=>'u_number','id|r_id'=>'user_id'];
        $page_config = array(
            'page' => input('get.offset', 1),
            'list_rows' => input('get.limit', 10),
        );

        $data = $this
            ->alias('a')
            ->field('a.*,b.r_name,c.u_number,d.phone')
            ->join('rooms b','a.room_id = b.id','left')
            ->join('users c','a.user_id = c.user_id','left')
            ->join('withdrawal_info d','a.user_id = d.user_id','left')
            ->where(true)
            ->paginate($page_config);

        foreach($data as $key => $value){
            $open = unserialize($value['open']);
            $data[$key]['withdraw'] = $open['withdraw'];
            $data[$key]['recharge'] = $open['recharge'];
            $data[$key]['exchange'] = $open['exchange'];
        }
        return $data;
    }

    public function roomProfitAdd()
    {
        $map = ['u_id'=>'u_number','id|r_id'=>'user_id'];
        $newData = input('post.');
       // dump($newData);
        $user_id = User::where(['u_number'=>$newData['u_id'] ])->value('user_id');
        if(!$user_id) return ['code'=>-100,'msg'=>'用户不存在'];

        $res = $this->where(['user_id'=>$user_id])->find();
        if($res) return ['code'=>-100,'msg'=>'该房间已报备'];

        if( $newData['percent'] < 0 || $newData['percent'] > 100 )  return ['code'=>-100,'msg'=>'收益比例不正确'];

        $percent = $newData['percent'] / 1000;

        $room_id = Room::where(['user_id'=>$user_id])->value('id');

        $control = serialize(['exchange'=>'1','withdraw'=>'1','recharge'=>'1']);  //二级密码控制
        $open = serialize(['exchange'=>$newData['exchange'],'withdraw'=>$newData['withdraw'],'recharge'=>$newData['recharge']]);
        $arr = [
            'user_id' => $user_id,
            'room_id' => $room_id,
            'money' => 0,
            'percent' => $percent,
            'status' => $newData['status'],
            'control' => $control,
            'open' => $open   //兑换  提现  代充 控制
        ];

       $res =  $this->save($arr);
       if($res) return ['code'=>100,'msg'=>'报备成功'];
       else return ['code'=>-100,'msg'=>'报备失败'];

    }

    //修改状态
    public function changeStatus()
    {
        $id = input('id');

        $status = $this->where(['id'=>$id])->value('status');

        $new_status = $status == 1 ? 2 : 1;

        $res = $this->save(['status'=>$new_status,'update_time'=>time()],['id'=>$id]);
        if($res) return ['code'=>100,'msg'=>'修改成功'];
        else return ['code'=>-100,'msg'=>'修改失败'];

    }

    //代充记录
    public function RechargeRecord()
    {
        $id = input('id');
        $page_config = [
            'page' => input('page', 1),
            'list_rows' => input('limit', 10),
            'query' => [
                'id' => $id
            ]
        ];
        $user_id = $this->where(['id'=>$id])->value('user_id');

        $agentRechargeModel = new AgentRecharge();
        $data = $agentRechargeModel->where(['recharge_user_id'=>$user_id])->paginate($page_config);

        foreach($data as $key => $value){
            $userInfo = User::where(['user_id'=>$value['receive_user_id']])->field('nickname')->find();
//            $userInfo = User::where(['id'=>$value['receive_user_id']])->field('u_id,nickname')->find();

            $userInfo['nickname'] = preg_replace_callback('/@E(.{6}==)/', function ($r) {
                return base64_decode($r[1]);
            }, $userInfo['nickname']);

//            $data[$key]['receive_user_id'] = $userInfo['u_number'];
            $data[$key]['nickname'] = $userInfo['nickname'];
         //   $data[$key]['recharge_money'] = $value['recharge_money'];
            $data[$key]['recharge_diamonds'] = $value['recharge_diamonds'];

        }

//        return json($data);die;
        return ['data'=>$data,'id'=>$id];
    }

    //导出上周流水
    public function lastWeekFlow()
    {
        $last_week = [
            mktime(0, 0, 0, date('m'), date('d') - (date('w')==0?7:date('w')) + 1 - 7, date('Y')),
            mktime(23, 59, 59, date('m'), date('d') - (date('w')==0?7:date('w')) + 7 - 7, date('Y'))
        ];

        $roomInfo =  $this->where(['status'=>1])->select();
        $data = [];
       foreach ($roomInfo as $key => $value){

           //    halt($roomInfo);
           $arr['percent'] = $value['percent'] * 10;
           $arr['create_time'] = $value['create_time'];

           $arr['r_name'] = Room::where(['id'=>$value['room_id']])->value('r_name');

           $arr['u_id'] = User::where(['id'=>$value['user_id']])->value('u_id');
           $alipayInfo = WithdrawalInfo::where(['user_id'=>$value['user_id']])->field('alipay_card,alipay_name')->find();

           $arr['alipay_card'] = $alipayInfo['alipay_card'];
           $arr['alipay_name'] = $alipayInfo['alipay_name'];

//           if( $value['create_time'] > $last_week[0])  $last_week[0] = $value['create_time'];
//           $lastWeekProfit =GiftRecord::where([['room_id','eq',$value['room_id']],['create_time','between',[$last_week[0],$last_week[1]]]])->sum('gift_price');
//           $arr['lastWeekProfit'] = $lastWeekProfit ? $lastWeekProfit : 0;

           $lastWeekProfit = 0;

           for($i = 0;$i < 7;$i++){
               $dates = date('Y-m-d',$last_week[0] + $i * 24 * 3600);

               $start_time = strtotime($dates);
               $end_time = strtotime($dates.' 23:59:59');

               $flowing = GiftRecord::where([['room_id','=',$value['room_id']],['create_time','between',[$start_time,$end_time]]])
                   ->sum('get_money');

               $arr[$dates] = $flowing ? floor(( $flowing / $value['percent'] )) : 0;
               $lastWeekProfit += $arr[$dates];
               $cellTitle[] = [$dates,$dates];
           }
           $arr['lastWeekProfit'] = $lastWeekProfit ? $lastWeekProfit : 0;
           $arr['money'] = floor($lastWeekProfit * 0.015 );
           $data[] = $arr;
       }
        $fileName = '报备房间流水';
        $remarkData = ['房间流水'];
        $cellTitle = [
            ['r_name','房间名'],
            ['u_id','厅主ID'],
            ['alipay_name','支付宝姓名'],
            ['alipay_card','支付宝账号'],
            ['percent','返现比例'],
            ['money','打款金钱'],
            ['create_time','创建时间'],
            ['lastWeekProfit','上周流水'],
        ];

        for($i = 0;$i < 7;$i++){
            $dates = date('Y-m-d',$last_week[0] + $i * 24 * 3600);
            $cellTitle[] = [$dates,$dates];
        }
       // $arr = array_merge($arr);

        $excelObj = new \app\common\api\Excel();
        $excelObj->exportExcel($fileName,$remarkData,$cellTitle,$data);

    }

}